extern "C"
{
#include <config.h>
#include <epan/epan.h>
#include <epan/filesystem.h>
}

#include <stdlib.h>
#include <crtdbg.h>

#include "Model.h"
#include "Communicator.h"
#include "InputMessage.h"
#include "OutputMessage.h"

using namespace std;

extern void RunTestLoop(const char* filename, Model &model);

int main(int argc, char* argv[])
{
#ifdef _DEBUG
//	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_ALWAYS_DF );
//	_CrtSetBreakAlloc(21346);
#endif

	// This is for libwireshark to know where to search for plugins.
	char *init_progfile_dir_error;
	init_progfile_dir_error = init_progfile_dir(argv[0]);

	if (init_progfile_dir_error != NULL) 
	{
		fprintf(stderr, "Can't get pathname of EpanServer program: %s.\n", init_progfile_dir_error);
	}

	Model model;

	if (argc>1)
	{
		RunTestLoop(argv[1], model);
		return 0;
	}
	
	try
	{
		Communicator comm;
		while (true)
		{
			pInputMessage nextMsg = comm.ReadMessage();
			POutputMessage response = nextMsg->Process(&model);
			if ( response.get() )
			{
				comm.WriteMessage(*response);
			} else {
				break;
			}
		}
	}
	catch (...)
	{
		return 1;
	}

	return 0;
}